package com.woniu.common.utils;

import com.woniu.common.dto.MinioProp;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

/**
 * @program: day09014
 * @description:
 * @create: 2024-09-23 11:29
 **/
@Slf4j
@Component
public class MinioUtils {

    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioProp minioProp;


    /**
     * 创建bucket
     */
    public void createBucket(String bucketName) {
        BucketExistsArgs bucketExistsArgs = BucketExistsArgs.builder().bucket(bucketName).build();
        MakeBucketArgs makeBucketArgs = MakeBucketArgs.builder().bucket(bucketName).build();
        try {
            //判断创建的桶（存放图片）是否存在
            if (minioClient.bucketExists(bucketExistsArgs))
                return;
            minioClient.makeBucket(makeBucketArgs);
        } catch (Exception e) {
            log.error("创建桶失败：{}", e.getMessage());
            throw new RuntimeException(e);
        }
    }

    /**
     * @param file       文件
     * @param bucketName 存储桶
     * @return
     */
    public ResponseData uploadFile(MultipartFile file, String bucketName) throws Exception {
        // 判断上传文件是否为空
        if (null == file || 0 == file.getSize()) {
            return new ResponseData<>().fail(ResponseEnum.FAIL);
        }
        // 判断存储桶是否存在
        createBucket(bucketName);
        // 文件名
        String originalFilename = file.getOriginalFilename();
        // 新的文件名 = 存储桶名称_时间戳.后缀名
        String fileName = bucketName + "_" + System.currentTimeMillis() + originalFilename.substring(originalFilename.lastIndexOf("."));
        // 开始上传
        InputStream inputStream = file.getInputStream();
        PutObjectArgs args = PutObjectArgs.builder().bucket(bucketName).object(fileName)
                .stream(inputStream, inputStream.available(), -1).build();
        minioClient.putObject(args); //上传服务中
        String imgPaht = minioProp.getEndPoint() + "/" + bucketName + "/" + fileName;
        return new ResponseData<>().ok(imgPaht);
//        return new ResponseData(200, "操作成功", imgPaht);
    }
}
